package com.dht.xiao.jianye.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.dht.xiao.jianye.R;
import com.dht.xiao.jianye.base.App;
import com.dht.xiao.jianye.utils.OpenManager;

public class UsbDoorActivity extends Activity {

	public static final String TAG = "cn.wch.wchusbdriver";
	private static final String ACTION_USB_PERMISSION = "cn.wch.wchusbdriver.USB_PERMISSION";

	private EditText readText;
	private EditText writeText;

	private boolean isOpen;
	private Handler handler;
	private UsbDoorActivity activity;

	private Button writeButton, clearButton;

	public int baudRate;
	public byte stopBit;
	public byte dataBit;
	public byte parity;
	public byte flowControl;



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_new);
//		App.driver = new CH34xUARTDriver(
//				(UsbManager) getSystemService(Context.USB_SERVICE), this,
//				ACTION_USB_PERMISSION);
		initUI();
//		if (!App.driver.UsbFeatureSupported())// 判断系统是否支持USB HOST
//		{
//			Dialog dialog = new AlertDialog.Builder(UsbDoorActivity.this)
//					.setTitle("提示")
//					.setMessage("您的手机不支持USB HOST，请更换其他手机再试！")
//					.setPositiveButton("确认",
//							new DialogInterface.OnClickListener() {
//
//								@Override
//								public void onClick(DialogInterface arg0,
//													int arg1) {
//									System.exit(0);
//								}
//							}).create();
//			dialog.setCanceledOnTouchOutside(false);
//			dialog.show();
//		}
//		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 保持常亮的屏幕的状态
//		isOpen = false;
//
//		writeButton.setEnabled(false);
//		activity = this;
//
//		open();
//
//
		OpenManager openManagerNew = new OpenManager(this);
		openManagerNew.setCallBack(new OpenManager.OpenCallBack() {

			@Override
			public void onReceiveData(String data,String command, long num, String status) {

			}

			@Override
			public void onInit(Boolean data) {

			}
		});
		writeButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				openManagerNew.sendData("574B4C590901820182");
//				byte[] to_send = toByteArray(writeText.getText().toString());        //以16进制发送
//				LogPlus.e(writeText.getText().toString());
//				int retval = App.driver.WriteData(to_send, to_send.length);//写数据，第一个参数为需要发送的字节数组，第二个参数为需要发送的字节长度，返回实际发送的字节长度
//				if (retval < 0)
//					Toast.makeText(UsbDoorActivity.this, "Write failed!",
//							Toast.LENGTH_SHORT).show();
			}
		});


		handler = new Handler() {
			public void handleMessage(Message msg) {
				readText.append((String) msg.obj);
			}
		};

	}

	private void open() {
		if (!isOpen) {
			int retval = App.driver.ResumeUsbPermission();
			if (retval == 0) {
				retval = App.driver.ResumeUsbList();
				if (retval == -1)// ResumeUsbList方法用于枚举CH34X设备以及打开相关设备
				{
					Toast.makeText(UsbDoorActivity.this, "Open failed!",
							Toast.LENGTH_SHORT).show();
					App.driver.CloseDevice();
				} else if (retval == 0) {
					if (App.driver.mDeviceConnection != null) {
						if (!App.driver.UartInit()) {//对串口设备进行初始化操作
							Toast.makeText(UsbDoorActivity.this, "Initialization failed!",
									Toast.LENGTH_SHORT).show();
							return;
						}
						Toast.makeText(UsbDoorActivity.this, "Device opened",
								Toast.LENGTH_SHORT).show();
						isOpen = true;

						writeButton.setEnabled(true);
						configData();
						new readThread().start();//开启读线程读取串口接收的数据
					} else {
						Toast.makeText(UsbDoorActivity.this, "Open failed!",
								Toast.LENGTH_SHORT).show();
					}
				} else {

					AlertDialog.Builder builder = new AlertDialog.Builder(activity);
					builder.setIcon(R.drawable.ic_launcher_background);
					builder.setTitle("未授权限");
					builder.setMessage("确认退出吗？");
					builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							System.exit(0);
						}
					});
					builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub

						}
					});
					builder.show();

				}
			}
		} else {

			writeButton.setEnabled(false);
			isOpen = false;
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			App.driver.CloseDevice();
		}

	}

	private void configData() {
		baudRate = 9600;
		stopBit = 1;
		dataBit = 8;
		parity = 0;
		flowControl = 0;
		if (App.driver.SetConfig(baudRate, dataBit, stopBit, parity,//??????????????????????????????
				flowControl)) {
			Toast.makeText(UsbDoorActivity.this, "Config successfully",
					Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(UsbDoorActivity.this, "Config failed!",
					Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
	}


	@Override
	public void onDestroy() {
		isOpen = false;
		App.driver.CloseDevice();
		super.onDestroy();
	}

	//???????
	private void initUI() {
		readText = (EditText) findViewById(R.id.ReadValues);
		writeText = (EditText) findViewById(R.id.WriteValues);
		writeButton = (Button) findViewById(R.id.WriteButton);
		clearButton = (Button) findViewById(R.id.clearButton);
		/* by default it is 9600 */

		clearButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				readText.setText("");
			}
		});
		return;
	}

	private class readThread extends Thread {

		public void run() {

			byte[] buffer = new byte[4096];

			while (true) {

				Message msg = Message.obtain();
				if (!isOpen) {
					break;
				}
				int length = App.driver.ReadData(buffer, 4096);
				if (length > 0) {
					String recv = toHexString(buffer, length);        //以16进制输出
//					String recv = new String(buffer, 0, length);		//以字符串形式输出
					msg.obj = recv;
					handler.sendMessage(msg);
				}
			}
		}
	}

	/**
	 * 将byte[]数组转化为String类型
	 *
	 * @param arg    需要转换的byte[]数组
	 * @param length 需要转换的数组长度
	 * @return 转换后的String队形
	 */
	private String toHexString(byte[] arg, int length) {
		String result = new String();
		if (arg != null) {
			for (int i = 0; i < length; i++) {
				result = result
						+ (Integer.toHexString(
						arg[i] < 0 ? arg[i] + 256 : arg[i]).length() == 1 ? "0"
						+ Integer.toHexString(arg[i] < 0 ? arg[i] + 256
						: arg[i])
						: Integer.toHexString(arg[i] < 0 ? arg[i] + 256
						: arg[i])) + " ";
			}
			return result;
		}
		return "";
	}

	/**
	 * 将String转化为byte[]数组
	 *
	 * @param arg 需要转换的String对象
	 * @return 转换后的byte[]数组
	 */
	private byte[] toByteArray(String arg) {
		if (arg != null) {
			/* 1.先去除String中的' '，然后将String转换为char数组 */
			char[] NewArray = new char[1000];
			char[] array = arg.toCharArray();
			int length = 0;
			for (int i = 0; i < array.length; i++) {
				if (array[i] != ' ') {
					NewArray[length] = array[i];
					length++;
				}
			}
			/* 将char数组中的值转成一个实际的十进制数组 */
			int EvenLength = (length % 2 == 0) ? length : length + 1;
			if (EvenLength != 0) {
				int[] data = new int[EvenLength];
				data[EvenLength - 1] = 0;
				for (int i = 0; i < length; i++) {
					if (NewArray[i] >= '0' && NewArray[i] <= '9') {
						data[i] = NewArray[i] - '0';
					} else if (NewArray[i] >= 'a' && NewArray[i] <= 'f') {
						data[i] = NewArray[i] - 'a' + 10;
					} else if (NewArray[i] >= 'A' && NewArray[i] <= 'F') {
						data[i] = NewArray[i] - 'A' + 10;
					}
				}
				/* 将 每个char的值每两个组成一个16进制数据 */
				byte[] byteArray = new byte[EvenLength / 2];
				for (int i = 0; i < EvenLength / 2; i++) {
					byteArray[i] = (byte) (data[i * 2] * 16 + data[i * 2 + 1]);
				}
				return byteArray;
			}
		}
		return new byte[]{};
	}


}
